package com.classic.duanzhi;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.classic.base.BaseActivity;
import com.classic.utils.helper;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 单个段子页面
 */
public class AnEpisodeActivity extends BaseActivity {
    private RefreshLayout refreshLayout;
    private int pagerNumber = 1;
    private RecyclerView mRecyclerView;

    private CustomAdapter mAdapter;
    private List<View> mAdViewList;
    private HashMap<View, Integer> mAdViewPositionMap = new HashMap<>();


    @Override
    protected int getLayoutId() {
        return R.layout.ad_activity_an_episode;
    }

    public static void starThis(FragmentActivity activity) {
        Intent intent = new Intent(activity, AnEpisodeActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected void initView() {
        refreshLayout = findViewById(R.id.refreshLayout);
        mRecyclerView = findViewById(R.id.listView);

        mAdapter = new CustomAdapter();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mAdapter);
        initNativeExpressAD();
        refreshLayout.autoRefresh();
        //刷新
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                initData(pagerNumber);
            }
        });
        //加载更多
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                initData(pagerNumber + 1);
            }
        });
    }

    @Override
    protected void initData() {
    }


    @Override
    public String getActivityTitle() {
        return "经典段子";
    }


    void initData(final int number) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                Document doc;
                try {
                    doc = Jsoup.connect("http://duanziwang.com/page/" + number + "/").get();
                    Elements post = doc.getElementsByClass("post");
                    final List<DZDataBen1> dataBens = new ArrayList<>();
                    for (int i = 0; i < post.size(); i++) {
                        Element element = post.get(i);
                        element.text();
                        Elements elementsByClass = element.getElementsByClass("post-title");
                        Elements c = element.getElementsByClass("post-content");
                        Elements c1 = element.getElementsByClass("post-meta");
                        DZDataBen1 dataBen = new DZDataBen1(elementsByClass.text(), c.text(), c1.text().split(" ")[0]);
                        dataBens.add(dataBen);
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            pagerNumber = number;
                            mAdapter.setData(dataBens);
                            refreshLayout.finishRefresh();
                            refreshLayout.finishLoadMore();
                        }
                    });
                } catch (IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            refreshLayout.finishRefresh();
                            refreshLayout.finishLoadMore();
                        }
                    });
                }
            }
        }.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    /**
     * 请求广告
     */
    private void initNativeExpressAD() {
    }


    /**
     * RecyclerView的Adapter
     */
    class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder> {

        static final int TYPE_DATA = 0;
        static final int TYPE_AD = 1;
        private List<Object> mData;
        private List<DZDataBen1> listData;
        private List<View> ADData;

        CustomAdapter() {
            this.mData = new ArrayList<>();
            this.ADData = new ArrayList<>();
            this.listData = new ArrayList<>();
        }

        public void setData(List<DZDataBen1> d) {
            if (pagerNumber == 1) {
                listData = new ArrayList<>();
                listData.addAll(d);
            } else {
                listData.addAll(d);
            }
            mData = new ArrayList<>();
            mData.addAll(listData);
            notifyDataSetChanged();
        }

        // 把返回的NativeExpressADView添加到数据集里面去
        public void addADViewToPosition(int position, View adView) {
            if (position >= 0 && position < mData.size() && adView != null) {
                mData.add(position, adView);
            }
        }

        // 移除NativeExpressADView的时候是一条一条移除的
        void removeADView(int position, View adView) {
            mData.remove(position);
            mAdapter.notifyItemRemoved(position); // position为adView在当前列表中的位置
            mAdapter.notifyItemRangeChanged(0, mData.size() - 1);
        }

        @Override
        public int getItemCount() {
            if (mData != null) {
                return mData.size();
            } else {
                return 0;
            }
        }

        @Override
        public int getItemViewType(int position) {
            return mData.get(position) instanceof View ? TYPE_AD : TYPE_DATA;
        }

        @Override
        public void onBindViewHolder(@NonNull final CustomViewHolder holder, final int position) {
            int type = getItemViewType(position);
            if (TYPE_AD == type) {
                final View adView = (View) mData.get(position);
                mAdViewPositionMap.put(adView, position); // 广告在列表中的位置是可以被更新的
                if (holder.container.getChildCount() > 0
                        && holder.container.getChildAt(0) == adView) {
                    return;
                }

                if (holder.container.getChildCount() > 0) {
                    holder.container.removeAllViews();
                }

                if (adView.getParent() != null) {
                    ((ViewGroup) adView.getParent()).removeView(adView);
                }

                holder.container.addView(adView);
            } else {
                DZDataBen1 o = (DZDataBen1) mData.get(position);
                holder.time.setText(o.getDate());
                holder.week.setText(helper.getWeek(o.getDate()));
                holder.sub.setText(TextUtils.isEmpty(o.getContent()) ? o.getTitle() : o.getContent());
//                customViewHolder.title.setText(((NormalItem) mData.get(position)).getTitle());
            }
        }

        @NonNull
        @Override
        public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
            int layoutId = (viewType == TYPE_AD) ? R.layout.ad_item_express_ad : R.layout.ad_item_anepisode_layout;
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(layoutId, null);
            return new CustomViewHolder(view);
        }

        void setADData(List<View> ADData) {
            this.ADData = ADData;
            setData(listData);
        }

        class CustomViewHolder extends RecyclerView.ViewHolder {
            TextView title, week, sub, time;
            public ViewGroup container;

            CustomViewHolder(View view) {
                super(view);
                title = view.findViewById(R.id.title);
                container = view.findViewById(R.id.express_ad_container);

                time = view.findViewById(R.id.tv_time);
                week = view.findViewById(R.id.tv_week);
                sub = view.findViewById(R.id.tv_subtitle);
            }
        }
    }


    private static final String TAG = AnEpisodeActivity.class.getSimpleName();
}
